package com.zt.bus.wx.service;

import com.zt.bus.constant.BusConstant;
import com.zt.bus.line.inter.RefundDetailMapper;
import com.zt.bus.line.inter.RefundMapper;
import com.zt.bus.line.model.Refund;
import com.zt.bus.line.model.RefundDetail;
import com.zt.bus.order.model.Order;
import com.zt.bus.order.model.OrderPayment;
import com.zt.bus.order.service.OrderBackService;
import com.zt.bus.order.service.OrderPaymentService;
import com.zt.bus.util.CollectionUtil;
import com.zt.bus.wx.util.AppHttpUtils;
import com.zt.bus.wx.util.HttpUtils;
import com.zt.bus.wx.util.PayUtil;
import com.zt.bus.wx.util.XmlUtil;
import com.zt.servlet.FieldAlias;
import com.zt.servlet.ReqBean;
import com.zt.system.model.BusinessException;
import com.zt.system.model.SqlBuilder;
import com.zt.system.service.BaseService;
import com.zt.system.service.IFieldAliasService;
import com.zt.util.PropertiesUtil;
import com.zt.util.StringUtil;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import sun.rmi.runtime.Log;

@Service
public class WxPayService extends BaseService {

    private static final Logger LOG = Logger.getLogger(WxPayService.class);

    private static final String ORDER_PAY = "https://api.mch.weixin.qq.com/pay/unifiedorder"; // 统一下单

    private static final String ORDER_PAY_QUERY = "https://api.mch.weixin.qq.com/pay/orderquery"; // 支付订单查询

    private static final String ORDER_REFUND = "https://api.mch.weixin.qq.com/secapi/pay/refund"; // 申请退款

    private static final String ORDER_REFUND_QUERY = "https://api.mch.weixin.qq.com/pay/refundquery"; // 申请退款

    private static final String APP_ID = PropertiesUtil.getProperty("wxPay.appId");

    private static final String MCH_ID = PropertiesUtil.getProperty("wxPay.mchId");

    private static final String API_SECRET = PropertiesUtil.getProperty("wxPay.mchKey");

    private static final String APP_APP_ID = PropertiesUtil.getProperty("wxAppPay.appId");

    private static final String APP_MCH_ID = PropertiesUtil.getProperty("wxAppPay.mchId");

    private static final String APP_API_SECRET = PropertiesUtil.getProperty("wxAppPay.mchKey");

    @Autowired
    private OrderPaymentService orderPaymentService;

    @Autowired
    private OrderBackService orderBackService;


    public OrderPayment orderPayRefund(String tradeNo, String payPlatformNo,String orderPayPlatform, String orderFee, String refundFee) {

        LOG.info("微信退款开始");

        if (StringUtil.isEmpty(tradeNo) || StringUtil.isEmpty(payPlatformNo)) {
            throw new BusinessException("交易订单号不存在!");
        }
        if (StringUtil.isEmpty(orderFee) || StringUtil.isEmpty(refundFee)) {
            throw new BusinessException("退订的金额为空!");
        }

        Map<String, String> restmap = null;
        OrderPayment orderPayment = null;
        String restxml = "";
        try {
            Map<String, String> parm = new HashMap<String, String>();
            parm.put("nonce_str", PayUtil.getNonceStr());
            parm.put("transaction_id", payPlatformNo);
//            parm.put("out_trade_no", tradeNo);//订单号
            parm.put("out_refund_no", PayUtil.getRefundNo()); //退款单号
            //TODO 金额现在默认写死为1分钱
            parm.put("total_fee", "2"); // 订单总金额 从业务逻辑获取 单位分 只能为整数
            parm.put("refund_fee", "1"); // 退款金额 单位分 只能为整数
            parm.put("refund_account", "REFUND_SOURCE_UNSETTLED_FUNDS");//退款方式
            //String restxml = HttpUtils.posts(ORDER_REFUND, XmlUtil.xmlFormat(parm, false));
            if(orderPayPlatform.equals(BusConstant.PayPlatform.WEIXIN_APP)) {
                parm.put("appid", APP_APP_ID);
                parm.put("op_user_id", APP_MCH_ID);
                parm.put("mch_id", APP_MCH_ID);
                parm.put("sign", PayUtil.getSign(parm, APP_API_SECRET));
                restxml = AppHttpUtils.posts(ORDER_REFUND, XmlUtil.xmlFormat(parm, false));
            } else if(orderPayPlatform.equals(BusConstant.PayPlatform.WEIXIN_WEB)) {
                parm.put("appid", APP_ID);
                parm.put("op_user_id", MCH_ID);
                parm.put("mch_id", MCH_ID);
                parm.put("sign", PayUtil.getSign(parm, API_SECRET));
                restxml = HttpUtils.posts(ORDER_REFUND, XmlUtil.xmlFormat(parm, false));
            }
            System.out.println(restxml);
            restmap = XmlUtil.xmlParse(restxml);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }

        Map<String, String> refundMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(restmap) && "SUCCESS".equals(restmap.get("return_code"))) {
            if("SUCCESS".equals(restmap.get("result_code"))) {
                refundMap.put("transaction_id", restmap.get("transaction_id"));
                refundMap.put("out_trade_no", restmap.get("out_trade_no"));
                refundMap.put("refund_id", restmap.get("refund_id"));
                refundMap.put("out_refund_no", restmap.get("out_refund_no"));

                //退款成功修改退款状态，更新退款流水号
                orderPayment = orderPaymentService.getByPrimaryKey(tradeNo);
                orderPayment.setPayPlatformNo(restmap.get("refund_id"));
                orderPayment.setPayStatus(BusConstant.OrderBackStatus.REFUND_SUCCESS);
                orderPayment.setPayTime(new Date());
                orderPayment.setResultMsg(tradeNo + "退款成功,微信退款单号:" + restmap.get("refund_id"));
                orderPaymentService.updateOrderPayment(orderPayment);
                orderBackService.updateOrderBackStatus(orderPayment.getOrderId(),BusConstant.OrderBackStatus.REFUND_SUCCESS);
                LOG.info("订单退款：订单" + restmap.get("out_trade_no") + "退款成功，商户退款单号" + restmap.get("out_refund_no") + "，微信退款单号"
                        + restmap.get("refund_id"));
            } else {
                //退款失败修改退款状态，更新退款流水号
                orderPayment = orderPaymentService.getByPrimaryKey(tradeNo);
                orderPayment.setPayPlatformNo(restmap.get("refund_id"));
                orderPayment.setPayStatus(BusConstant.OrderBackStatus.REFUND_FAIL);
                orderPayment.setPayTime(new Date());
                if (CollectionUtil.isNotEmpty(restmap)) {
                    LOG.info("订单退款失败：" + restmap.get("err_code") + ":" + restmap.get("err_code_des"));
                    orderPayment.setResultMsg(tradeNo + "订单退款失败:" + restmap.get("err_code") + ":" + restmap.get("err_code_des"));
                }
                orderPaymentService.updateOrderPayment(orderPayment);
                orderBackService.updateOrderBackStatus(orderPayment.getOrderId(), BusConstant.OrderBackStatus.REFUND_FAIL);
            }

        } else {
            //退款失败修改退款状态，更新退款流水号
            orderPayment = orderPaymentService.getByPrimaryKey(tradeNo);
            orderPayment.setPayPlatformNo(restmap.get("refund_id"));
            orderPayment.setPayStatus(BusConstant.OrderBackStatus.REFUND_FAIL);
            orderPayment.setPayTime(new Date());
            if (CollectionUtil.isNotEmpty(restmap)) {
                LOG.info("订单退款失败：" + restmap.get("err_code") + ":" + restmap.get("err_code_des"));
                orderPayment.setResultMsg(tradeNo + "订单退款失败:" + restmap.get("err_code") + ":" + restmap.get("err_code_des"));
            }
            orderPaymentService.updateOrderPayment(orderPayment);
            orderBackService.updateOrderBackStatus(orderPayment.getOrderId(), BusConstant.OrderBackStatus.REFUND_FAIL);
        }
        LOG.info("微信退款结束");

        return orderPayment;
    }

}
